import Vue from 'vue'
import Vuex from 'vuex'
const projectName = require('/config/project')

Vue.use(Vuex)

import sfsHome from './modules/sfs/home.js'
import sfsOnemap from './modules/sfs/onemap.js'

const dynamicModules = {}
const files = require.context(`/src/projects/`, true, /\.js$/)

// console.log('filesKeys:', files.keys())
// let nowFiles = files
//   .keys()
//   .filter((file) => file != './index.js' && file.includes('modules'))
// console.log('nowFiles:', nowFiles)

const dynamicImportModules = (modules, file, splits, index = 0) => {
  if (index === 0 && splits[0] === 'modules') {
    ++index
  }
  if (splits.length === index + 1) {
    if ('index' === splits[index]) {
      modules[splits[index - 1]] = files(file).default
    } else {
      modules.modules[splits[index]] = files(file).default
    }
  } else {
    let tmpModules = {}
    if ('index' === splits[index + 1]) {
      tmpModules = modules
    } else {
      modules[splits[index]] = modules[splits[index]]
        ? modules[splits[index]]
        : { namespaced: true, modules: {} }
      tmpModules = modules[splits[index]]
    }
    dynamicImportModules(tmpModules, file, splits, ++index)
  }
}

files
  .keys()
  .filter(
    (file) =>
      file != './index.js' &&
      file.includes('store/modules') &&
      file.includes(projectName.name),
  )
  .forEach((file) => {
    let splits = file.replace(/(\.\/|.*store\/|\.js)/g, '').split('/')
    dynamicImportModules(dynamicModules, file, splits)
    // console.log('dynamicModules:', dynamicModules)
  })

export default new Vuex.Store({
  modules: {
    sfsHome,
    sfsOnemap,
    ...dynamicModules,
  },
  strict: process.env.NODE_ENV !== 'production',
})
